'''
Created on Dec 5, 2010

@author: mkiyer
'''
import argparse
import os
import logging
import subprocess

from config import PipelineConfig, JobConfig
from base import file_newer, JOB_SUCCESS, JOB_ERROR

def run_fastqc(fastq_file, output_html_file, output_data_file,
               fastqc_bin, tmp_dir, output_dir):
    # run fastqc program        
    args = [fastqc_bin, '-o', output_dir, fastq_file]
    logging.info("Running FastQC on file=%s args=%s" % (fastq_file, str(args)))
    if subprocess.call(args, cwd=output_dir) != 0:
        logging.error("Error running FastQC args='%s'" % (str(args)))
        return JOB_ERROR
    return JOB_SUCCESS

def fastqc_job(job_file, config_file, mate):
    config = PipelineConfig()
    config.from_xml(config_file)
    job  = JobConfig()
    job.from_cfg(job_file, config.output_dir) 
    if not os.path.exists(job.output_dir):
        logging.error("%s: output directory %s does not exist" % (job.name, job.output_dir))
        return JOB_ERROR
    fastq_file = job.fastq_files[mate]
    fastqc_html_file = job.fastqc_html_files[mate]
    fastqc_data_file = job.fastqc_data_files[mate]    
    # check output files
    if (file_newer(fastqc_html_file, fastq_file) and
        file_newer(fastqc_data_file, fastq_file)):
        logging.info("%s: Skipping FastQC on file %s" % (job.name, fastq_file))
        return JOB_SUCCESS
    # Run FastQC program
    return run_fastqc(fastq_file, fastqc_html_file, fastqc_data_file, 
                      config.fastqc_bin, config.tmp_dir, job.output_dir)

def main():
    logging.basicConfig(level=logging.DEBUG,
                        format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    parser = argparse.ArgumentParser()
    parser.add_argument("--mate", type=int, dest="mate")
    parser.add_argument("job_file")
    parser.add_argument("config_file")
    options = parser.parse_args()
    return fastqc_job(options.job_file, options.config_file, options.mate)

if __name__ == '__main__': 
    import sys
    sys.exit(main())